package com.sx.gongzhong.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.ImageAdapter;
import com.sx.gongzhong.adapter.MyFragmentPagerAdapter;
import com.sx.gongzhong.fragment.ConvennicAppealComFragment;
import com.sx.gongzhong.fragment.ConvennicAppealReplyFragment;
import com.sx.gongzhong.model.CommentBean;
import com.sx.gongzhong.model.ConvenniceAppealBean;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.pest.ConvenniceAppealDetailPest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.ConvenniceAppealDetailView;
import com.sx.gongzhong.widget.CustomDialog;
import com.sx.gongzhong.widget.InnerListView;
import com.sx.gongzhong.widget.LoadDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 便民诉求详情
 * Created by admin on 2018/1/4.
 */

public class ConvenniceAppealDetailActivity extends BaseActivity implements ConvenniceAppealDetailView,
        View.OnClickListener {
    @BindView(R.id.im_headerUrl)
    ImageView imHeaderUrl;
    @BindView(R.id.tv_Name)
    TextView tvName;
    @BindView(R.id.tv_appealTime)
    TextView tvAppealTime;
    @BindView(R.id.tv_handleStatus)
    TextView tvHandleStatus;
    @BindView(R.id.tv_appealType)
    TextView tvAppealType;
    @BindView(R.id.tv_praiseTimes)
    TextView tvPraiseTimes;
    @BindView(R.id.tv_PraiseAdd)
    TextView tv_PraiseAdd;
    @BindView(R.id.tv_readTimes)
    TextView tvReadTimes;
    @BindView(R.id.tv_Content)
    TextView tvContent;
    @BindView(R.id.imgListView)
    InnerListView imgListView;
    @BindView(R.id.tv_orgName)
    TextView tvOrgName;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.et_Comment)
    EditText etComment;
    @BindView(R.id.rl)
    RelativeLayout rl;

    private List<Fragment> fragments = new ArrayList<>();
    private String appealId;
    private boolean isParise = false;
    private ConvennicAppealComFragment ComFragment;
    private ConvenniceAppealBean detailBean;//诉求详情

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_convennic_appealdetail);
        setTitleName("便民诉求详情");
        ButterKnife.bind(this);
        setRightImage(R.mipmap.icon_nav_more);
        appealId = getIntent().getStringExtra("appealId");
        LoadDialog.show(ConvenniceAppealDetailActivity.this,"加载中...");
        new ConvenniceAppealDetailPest(this).getAppealDetail(appealId);
    }
    @Override
    public void showError(String message) {
        LoadDialog.dismiss(ConvenniceAppealDetailActivity.this);
        ToastUtils.showToast(ConvenniceAppealDetailActivity.this,message);
        if(message.equals("获取详情失败")){
            finish();
        }
    }
    @Override
    public void getAppealDetailSuccess(ConvenniceAppealBean bean) {
        LoadDialog.dismiss(ConvenniceAppealDetailActivity.this);
        detailBean = bean;
        initData();
    }

    private void initData() {
        if (detailBean.appeal != null){
            tvName.setText(detailBean.appeal.getName());
            RequestOptions options = new RequestOptions().centerCrop()
                    .placeholder(R.mipmap.img_head_default)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .circleCrop()
                    .error(R.mipmap.img_head_default);
            Glide.with(this)
                    .load(ServiceFactory.getUrl(detailBean.appeal.getHeaderUrl()))
                    .apply(options)
                    .into(imHeaderUrl);
        }
        tvAppealType.setText(detailBean.appealType != null ? "#"+detailBean.appealType.name:"");
        if (detailBean.handleStatus.equals("to_be_accepted")){
            tvHandleStatus.setText("待受理");
            tvHandleStatus.setBackgroundResource(R.drawable.shape_red_corner_50);
        }else if (detailBean.handleStatus.equals("accepted")){
            tvHandleStatus.setText("已受理");
            tvHandleStatus.setBackgroundResource(R.drawable.shape_green_corner_50);
        }else if (detailBean.handleStatus.equals("already_done")){
            tvHandleStatus.setText("已办结");
            tvHandleStatus.setBackgroundResource(R.drawable.shape_orige_corner_50);
        }
        if (!BaseUtil.isEmpty(detailBean.evaluationContent)){
            tvHandleStatus.setText("已评价");
            tvHandleStatus.setBackgroundResource(R.drawable.shape_orige_corner_50);
        }
        tvAppealTime.setText(detailBean.appealTime);
        tvReadTimes.setText(detailBean.readTimes);
        tvPraiseTimes.setText(detailBean.praiseTimes);
        tvContent.setText(detailBean.content);
        tvOrgName.setText(detailBean.orgName);
        if (detailBean.files != null && detailBean.files.size() > 0){
            imgListView.setVisibility(View.VISIBLE);
            ImageAdapter adapter = new ImageAdapter(this, R.layout.item_image, detailBean.files);
            imgListView.setAdapter(adapter);
        }else {
            imgListView.setVisibility(View.GONE);
        }

        List<String> titles = new ArrayList<>();
        titles.add("答复");
        titles.add("大众点评");

        Bundle bundle = new Bundle();
        bundle.putString("replyId",detailBean.id);

        ConvennicAppealReplyFragment replyFragment = new ConvennicAppealReplyFragment();
        replyFragment.setArguments(bundle);
        fragments.add(replyFragment);

        ComFragment = new ConvennicAppealComFragment();
        ComFragment.setArguments(bundle);
        fragments.add(ComFragment);

        tablayout.setTabMode(TabLayout.MODE_FIXED);
        //为TabLayout添加tab名称
        tablayout.addTab(tablayout.newTab().setText(titles.get(0)));
        tablayout.addTab(tablayout.newTab().setText(titles.get(1)));
        MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),
                fragments, titles);
        viewpager.setAdapter(pagerAdapter);
        //tabLayout加载viewpager
        tablayout.setupWithViewPager(viewpager);
        etComment.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (isLogin()){
                    if (keyCode == event.KEYCODE_ENTER &&
                            event.getAction() == KeyEvent.ACTION_DOWN) {
                        if (etComment.getText().toString().trim().length() == 0){
                            ToastUtils.showToast(ConvenniceAppealDetailActivity.this,"请输入内容");
                            return false;
                        }
                        new ConvenniceAppealDetailPest(ConvenniceAppealDetailActivity.this).addComment(appealId,etComment.getText().toString().trim());
                        return true;
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void addPraiseSuccess(Integer data) {
        tv_PraiseAdd.setVisibility(View.VISIBLE);
        Animation anim = AnimationUtils.loadAnimation(this,R.anim.praise);
        anim.setFillAfter(true);
        tv_PraiseAdd.startAnimation(anim);
        tvPraiseTimes.setText(data+"");
        isParise = true;
    }
    @Override
    public void addCommentSuccess(CommentBean data) {
        etComment.setText("");
        if (ComFragment != null){
            ComFragment.onRefresh();
        }
    }
    @Override
    public void deleteAppealSuccess(Boolean data) {
        LoadDialog.dismiss(ConvenniceAppealDetailActivity.this);
        ToastUtils.showToast(ConvenniceAppealDetailActivity.this,"删除成功");
        MyRxBus.get().post(new MsgEvent("ConvenniceAppealActivity",1,null));
        finish();
    }
    @OnClick({R.id.tv_praiseTimes,R.id.imv_Right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_praiseTimes://点赞
                if (isLogin()){
                    if (!isParise){
                        new ConvenniceAppealDetailPest(this).addPraise(appealId);
                    }else {
                        ToastUtils.showToast(ConvenniceAppealDetailActivity.this,"已点过赞");
                    }
                }
                break;
            case R.id.imv_Right://右上角按钮显示
                if (isLogin()){
                    String status = detailBean.handleStatus;
                    if (status.equals("already_done")){//已办结 可评价 且 不能删除
                        status = "appeal_undelte_caneval";
                    }else if (status.equals("accepted")){//已受理 不能删除
                        status = "undelte";
                    }
                    if (!BaseUtil.isEmpty(detailBean.evaluationContent)){//已评价 不可再评价 不能删除
                        status = "undelte";
                    }
                    if (detailBean.appeal != null){
                        createPop(detailBean.appeal.getId(),status);
                    }
                }
                break;
            case R.id.tv_evaluation://评价
                popupWindow.dismiss();
                startActivityForResult(new Intent(ConvenniceAppealDetailActivity.this,EvalActivity.class).putExtra("appealId",appealId),101);
                break;
            case R.id.tv_ShutUp://整个诉求禁言
                popupWindow.dismiss();
                createDialog(2,"禁言");
                break;
            case R.id.tv_Report://举报楼主
                popupWindow.dismiss();
                createDialog(3,"举报");
                break;
            case R.id.tv_Delete://删除诉求
                popupWindow.dismiss();
                createDialog(4,"删除");
                break;
            case R.id.tv_Cancel://取消弹框
                popupWindow.dismiss();
                break;
        }
    }
    /**
     * 删除/举报/禁言
     */
    public void createDialog(final int type,String title) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        CustomDialog dialog = builder.setMessage("确定" + title + "吗？").
                setBackButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setConfirmButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (type == 2){
                    createReport("forbiddenType", detailBean.id, "convenient_appeal");
                }else if (type == 3){
                    createReport("reportType",  detailBean.id, "convenient_appeal");
                }else if (type == 4){
                    LoadDialog.show(ConvenniceAppealDetailActivity.this,"删除中...");
                    new ConvenniceAppealDetailPest(ConvenniceAppealDetailActivity.this).deleteAppeal(appealId);
                }
            }
        }).create();
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == 101){
                detailBean.handleStatus = "undelte";
                tvHandleStatus.setText("已评价");
                tvHandleStatus.setBackgroundResource(R.drawable.shape_orige_corner_50);
            }
        }
    }
}
